package com.theaf.core.utils;

import java.text.DecimalFormat;
import java.util.Random;

/**
 * Created by Administrator on 2017/5/17.
 */
public class NumberUtils {
    public static String generateRandomNumber(int n){
        if(n<1){
            throw new IllegalArgumentException("随机数位数必须大于0");
        }
        return String.valueOf((int) Math.floor(Math.random()*9* Math.pow(10,n-1) + (long) Math.pow(10,n-1)));
    }

    public static String subZero(Double d){
        if(d == null){
            return "0";
        }
        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        return decimalFormat.format(d);
    }

    public static String keepTwoDecimals(Double d){
        if(d == null){
            return  "0.00";
        }
        DecimalFormat df   = new DecimalFormat("######0.00");
        return df.format(d);
    }

    public static String zeroAppend(int targetLength, String oriStr) {
        if(oriStr.length() >= targetLength){
            return oriStr;
        }
        StringBuffer strBuffer = new StringBuffer();
        for (int i = 0; i < (targetLength - oriStr.length()); i++) {
            strBuffer.append("0");
        }
        return strBuffer.toString() + oriStr;
    }

    /**
     * 数字转中文小写
     * @param si
     * @return
     */
    public static String transition(String si){
        String[]aa = {"","十","百","千","万","十万","百万","千万","亿","十亿"};
        String[]bb = {"一","二","三","四","五","六","七","八","九"};
        char[] ch = si.toCharArray();
        int maxindex = ch.length;

        StringBuilder result = new StringBuilder("");

        //  字符的转换
        //两位数的特殊转换
        if(maxindex == 2){
            for(int i = maxindex - 1 , j = 0;i >= 0 ; i-- , j++){
                if(ch[j] != 48){
                    if(j == 0 && ch[j] == 49){
                        result.append(aa[i]);
                    }else{
                        result.append(bb[ch[j]-49] + aa[i]);
                    }
                }
            }
        //其他位数的特殊转换，使用的是int类型最大的位数为十亿
        }else{
            for(int i = maxindex -1 ,j = 0 ;i >= 0; i-- , j++){
                if(ch[j] != 48){
                    result.append(bb[ch[j]-49]+aa[i]);
                }
            }
        }

        return result.toString();
    }


    //随机字符串生成
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public static Double twoDecimal(Double money) {
        DecimalFormat df   = new DecimalFormat("######0.00");
        return Double.parseDouble(df.format(money));

    }
}
